package org.oims.simpleserver.typehandler;

import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;

import java.sql.*;
import java.util.Calendar;

@MappedJdbcTypes(JdbcType.TIMESTAMP)
public class TimestampTypeHandler extends BaseTypeHandler<Calendar> {

    @Override
    public void setNonNullParameter(PreparedStatement preparedStatement, int i, Calendar calendar, JdbcType jdbcType) throws SQLException {
        preparedStatement.setTimestamp(i, new Timestamp(calendar.getTimeInMillis()));
    }

    @Override
    public Calendar getNullableResult(ResultSet resultSet, String s) throws SQLException {
        Timestamp tt = resultSet.getTimestamp(s);
        if (tt == null){
            return null;
        }else {
            Calendar cal = Calendar.getInstance();
            cal.setTime(tt);
            return cal;
        }
    }

    @Override
    public Calendar getNullableResult(ResultSet resultSet, int i) throws SQLException {
        Timestamp tt = resultSet.getTimestamp(i);
        if (tt == null){
            return null;
        }else {
            Calendar cal = Calendar.getInstance();
            cal.setTime(tt);
            return cal;
        }
    }

    @Override
    public Calendar getNullableResult(CallableStatement callableStatement, int i) throws SQLException {
        Timestamp tt = callableStatement.getTimestamp(i);
        if (tt == null){
            return null;
        }else {
            Calendar cal = Calendar.getInstance();
            cal.setTime(tt);
            return cal;
        }
    }
}
